package com.tring.ysyn.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tring.ysyn.entity.SysUser;
import com.tring.ysyn.mapper.SysUserMapper;
import com.tring.ysyn.model.dto.user.UserDTO;
import com.tring.ysyn.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author tring
 * @since 2022-10-31
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    /**
     * 根据账号查询用户
     * @param account
     * @return
     */
    @Override
    public SysUser findUserByAccount(String account) {
        LambdaQueryWrapper<SysUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysUser::getUserName, account);
        return getOne(queryWrapper);
    }

    /**
     * 修改密码
     * @param dto
     */
    @Override
    @Transactional
    public void updatePwd(UserDTO dto) {
        SysUser byId = getById(dto.getId());
        byId.setPassword(SaSecureUtil.md5BySalt(dto.getPassword(), byId.getUserName()));
        StpUtil.kickout(dto.getId());
        this.updateById(byId);
    }

    /**
     * 禁用/冻结用户
     * @param id
     */
    @Override
    @Transactional
    public void disableOrAble(String id) {
        SysUser sysUser = this.baseMapper.selectById(id);
        if (sysUser != null) {
            sysUser.setStatus(sysUser.getStatus() == 1 ? 0 : 1);
            StpUtil.kickout(sysUser.getId());
            baseMapper.updateById(sysUser);
        }
    }

}
